<?php

namespace App\Api\Controllers\CustomerApplets;

use App\Api\Controllers\Config\PayWaysController;
use App\Api\Controllers\Merchant\PayBaseController;
use App\Models\MemberCzList;
use App\Models\MemberList;
use App\Models\MemberSetJf;
use App\Models\MembershipCardLists;
use App\Models\Store;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use App\Api\Controllers\CustomerApplets\BaseController;
use App\Api\Controllers\CustomerApplets\UserAliPayMembershipCardController;
use EasyWeChat\Factory;
use Illuminate\Support\Facades\DB;

class UserMembershipCardController extends BaseController
{
    //微信公众号的appid
    protected $weChatServerAppId;
    //微信公众号的秘钥
    protected $weChatServerSecret;

    public function __construct()
    {
        $this->weChatServerAppId   = config('api.weChatServerAppId');
        $this->weChatServerSecret  = config('api.weChatServerSecret');
    }

    /**
     * 创建会员卡（微信）
     * 主要是针对于商户端进行创建
     */
    public function userCreateMemberCard(Request $request)
    {
        $requestAllData = $request->all();
        if(!isset($requestAllData['store_id']) || empty($requestAllData['store_id'])){
            return $this->responseDataJson(4002);
        }
        if(!isset($requestAllData['terminal_type']) || empty($requestAllData['terminal_type'])){
            return $this->responseDataJson(4003);
        }

        //先判断该门店是否可以创建会员卡
        $membership_card_lists = DB::table("membership_card_lists")->where(['store_id' =>$requestAllData['store_id'] , 'terminal_type' => $requestAllData['terminal_type']])->first();
        if(!empty($membership_card_lists)){
            return $this->responseDataJson(2, "该门店已经创建了会员卡，不可重复创建", "");
        }

        switch ($requestAllData['terminal_type']) {
            //微信会员卡
            case config("api.weChat"):

                $logo_url = $requestAllData['logo_url'] ?? ''; //是	string(128)	卡券的商户logo，建议像素为300*300
                $brand_name = $requestAllData['brand_name'] ?? ''; //是	string	商户名字,字数上限为12个汉字
                $code_type = $requestAllData['code_type'] ?? ''; //是 string(16) Code展示类型，"CODE_TYPE_TEXT" 文本 "CODE_TYPE_BARCODE" 一维码 "CODE_TYPE_QRCODE" 二维码 "CODE_TYPE_ONLY_QRCODE" 仅显示二维码 "CODE_TYPE_ONLY_BARCODE" 仅显示一维码 "CODE_TYPE_NONE" 不显示任何码型
                $title = $requestAllData['title'] ?? ''; //是	string	卡券名，字数上限为9个汉字 (建议涵盖卡券属性、服务及金额)
                $color = $requestAllData['color'] ?? ''; //是	string	券颜色。按色彩规范标注填写Color010-Color100
                $notice = $requestAllData['notice'] ?? ''; //是	string	卡券使用提醒，字数上限为16个汉字
                $description = $requestAllData['description'] ?? ''; //是	string	卡券使用说明，字数上限为1024个汉字
                $type = $requestAllData['type'] ?? ''; //是	string	使用时间的类型 支持固定时长有效类型 固定日期有效类型 永久有效类型( DATE_TYPE_PERMANENT)
                $quantity = $requestAllData['quantity'] ?? 100000000; //是	int	卡券库存的数量，不支持填写0，上限为100000000
                $supply_bonus = $requestAllData['supply_bonus'] ?? ''; //是,bool,显示积分，填写true或false，如填写true，积分相关字段均为必填;若设置为true则后续不可以被关闭
                $supply_balance = $requestAllData['supply_balance'] ?? ''; //是	bool 是否支持储值，填写true或false。如填写true，储值相关字段均为必 填 若设置为true则后续不可以被关闭。该字段须开通储值功能后方可使用
                $prerogative = $requestAllData['prerogative'] ?? ''; //是,string(3072),会员卡特权说明,限制1024汉字

                $background_pic_url = $requestAllData['background_pic_url'] ?? ''; //否 string（128）	商家自定义会员卡背景图，须 先调用 上传图片接口 将背景图上传至CDN，否则报错， 卡面设计请遵循 微信会员卡自定义背景设计规范
                $service_phone = $requestAllData['service_phone'] ?? ''; //否	string（24）	客服电话
                $get_limit = $requestAllData['get_limit'] ?? 1; //否	int	每人可领券的数量限制，建议会员卡每人限领一张
                $location_id_list_lon = $requestAllData['location_id_list_lon'] ?? ''; //否,门店位置经度。调用 POI门店管理接口 获取门店位置ID
                $location_id_list_lat = $requestAllData['location_id_list_lat'] ?? ''; //否,门店位置纬度。调用 POI门店管理接口 获取门店位置ID
                $custom_url_name = $requestAllData['custom_url_name'] ?? ''; //否	string（15）	自定义跳转外链的入口名字
                $custom_url = $requestAllData['custom_url'] ?? ''; //否	string（128）	自定义跳转的URL
                $custom_url_sub_title = $requestAllData['custom_url_sub_title'] ?? ''; //否	string（18）	显示在入口右侧的提示语
                $promotion_url_name = $requestAllData['promotion_url_name'] ?? ''; //否	string（15）	营销场景的自定义入口名称
                $promotion_url = $requestAllData['promotion_url'] ?? ''; //否	string（128）	入口跳转外链的地址链接
                $accept_category = $requestAllData['accept_category'] ?? ''; //否,string（512）,指定可用的商品类目，仅用于代金券类型 ，填入后将在券面拼写适用于xxx
                $reject_category = $requestAllData['reject_category'] ?? ''; //否,string（512）,指定不可用的商品类目，仅用于代金券类型 ，填入后将在券面拼写不适用于xxxx
                $can_use_with_other_discount = $requestAllData['can_use_with_other_discount'] ?? ''; //否,bool,不可以与其他类型共享门槛，填写false时系统将在使用须知里 拼写“不可与其他优惠共享”，填写true时系统将在使用须知里 拼写“可与其他优惠共享”，默认为true
                $abstract = $requestAllData['abstract'] ?? ''; //否,string（24）,封面摘要简介
                $icon_url_list = $requestAllData['icon_url_list'] ?? ''; //否,string（128）,封面图片列表，仅支持填入一个封面图片链接，上传图片接口 上传获取图片获得链接，填写 非CDN链接会报错，并在此填入。 建议图片尺寸像素850*350
                $text_image_list = $requestAllData['text_image_list'] ?? ''; //否	JSON结构	图文列表，显示在详情内页 ，优惠券券开发者须至少传入 一组图文列表
                $time_limit = $requestAllData['time_limit'] ?? ''; //否,JSON结构,使用时段限制，包含以下字段
                $business_service = $requestAllData['business_service'] ?? ''; //否	arry	商家服务类型： BIZ_SERVICE_DELIVER 外卖服务； BIZ_SERVICE_FREE_PARK 停车位； BIZ_SERVICE_WITH_PET 可带宠物； BIZ_SERVICE_FREE_WIFI 免费wifi， 可多选用,连接
                $auto_activate = $requestAllData['auto_activate'] ?? 'true'; //否,int,设置为true时用户领取会员卡后系统自动将其激活，无需调用激活接口，详情见 自动激活
                $name_type = $requestAllData['name_type'] ?? ''; //否,string(24),会员信息类目半自定义名称，当开发者变更这类类目信息的value值时 可以选择触发系统模板消息通知用户。 FIELD_NAME_TYPE_LEVEL 等级 FIELD_NAME_TYPE_COUPON 优惠券 FIELD_NAME_TYPE_STAMP 印花 FIELD_NAME_TYPE_DISCOUNT 折扣 FIELD_NAME_TYPE_ACHIEVEMEN 成就 FIELD_NAME_TYPE_MILEAGE 里程 FIELD_NAME_TYPE_SET_POINTS 集点 FIELD_NAME_TYPE_TIMS 次数
                $url = $requestAllData['url'] ?? ''; //否,string(24),会员信息类目自定义名称，当开发者变更这类类目信息的value值时,不会触发系统模板消息通知用户
                $activate_url = $requestAllData['activate_url'] ?? ''; //否,string（128）,激活会员卡的url
                $custom_cell1 = $requestAllData['custom_cell1'] ?? ''; //否 json格式，自定义会员信息类目，会员卡激活后显示
                $cost_money_unit = $requestAllData['cost_money_unit'] ?? ''; //否,int,消费金额。以分为单位
                $increase_bonus = $requestAllData['increase_bonus'] ?? ''; //否,int,对应增加的积分
                $max_increase_bonus = $requestAllData['max_increase_bonus'] ?? ''; //否,int,用户单次可获取的积分上限
                $init_increase_bonus = $requestAllData['init_increase_bonus'] ?? ''; //否,int,初始设置积分
                $cost_bonus_unit = $requestAllData['cost_bonus_unit'] ?? ''; //否,int,每使用X积分
                $reduce_money = $requestAllData['reduce_money'] ?? ''; //否,int	抵扣xx元，（这里以分为单位）
                $least_money_to_use_bonus = $requestAllData['least_money_to_use_bonus'] ?? ''; //否,int,抵扣条件，满xx元（这里以分为单位）可用
                $max_reduce_bonus = $requestAllData['max_reduce_bonus'] ?? ''; //否,int,抵扣条件，单笔最多使用xx积分
                $discount = $requestAllData['discount'] ?? ''; //否,int,折扣，该会员卡享受的折扣优惠,填10就是九折

                $accessToken = $this->getWeChatAccessToken($this->weChatServerAppId, $this->weChatServerSecret);
                $accessToken = json_decode($accessToken, true);
                if (!isset($accessToken['access_token']) || empty($accessToken['access_token'])) {
                    return $this->responseDataJson(202,"access_token获取失败","");
                }
                $accessToken = $accessToken['access_token'];
                Log::info('access_token: '.$accessToken);
                $req_url = "https://api.weixin.qq.com/card/create?access_token=".$accessToken;

                if($supply_bonus) {
                    $supply_bonus = true;
                } else {
                    $supply_bonus =  false;
                }
                if($supply_balance) {
                    $supply_balance = true;
                } else {
                    $supply_balance =  false;
                }
                if($auto_activate) {
                    $auto_activate = true;
                } else {
                    $auto_activate =  false;
                }
                if($can_use_with_other_discount) {
                    $can_use_with_other_discount = true;
                } else {
                    $can_use_with_other_discount =  false;
                }

                $requestCouponData = [
                    'card' => [
                        'card_type' => 'MEMBER_CARD', //是
                        'member_card' => [
                            "base_info" => [ //是	JSON	基本的卡券数据，见下表，所有卡券类型通用。
                                "logo_url" => $logo_url,
                                "brand_name" => $brand_name,
                                "code_type" => $code_type,
                                "title" => $title,
                                "color" => $color,
                                "notice" => $notice,
                                "description" => $description,
                                "date_info" => [ //是	JSON	使用日期，有效期的信息
                                    "type" => $type
                                ],
                                "sku" => [ //是	JSON	商品信息
                                    "quantity" => (int)$quantity
                                ],
                                "get_limit" => (int)$get_limit,
//                                "use_custom_code" => false,
//                                "can_give_friend" => true,
//                                "need_push_on_view" => true
                            ],
                            "supply_bonus" => $supply_bonus,
                            "supply_balance" => $supply_balance,
                            "prerogative" => $prerogative,
                        ]
                    ]
                ];
                if ($background_pic_url) $requestCouponData['card']['member_card']['background_pic_url'] = $background_pic_url;
                if ($service_phone) $requestCouponData['card']['member_card']['base_info']['service_phone'] = $service_phone;
                if ($location_id_list_lon && $location_id_list_lat) $requestCouponData['card']['member_card']['base_info']['location_id_list'] = [(int)$location_id_list_lon, (int)$location_id_list_lat];
                if ($custom_url_name) $requestCouponData['card']['member_card']['base_info']['custom_url_name'] = $custom_url_name;
                if ($custom_url) $requestCouponData['card']['member_card']['base_info']['custom_url'] = $custom_url;
                if ($custom_url_sub_title) $requestCouponData['card']['member_card']['base_info']['custom_url_sub_title'] = $custom_url_sub_title;
                if ($promotion_url_name) $requestCouponData['card']['member_card']['base_info']['promotion_url_name'] = $promotion_url_name;
                if ($promotion_url) $requestCouponData['card']['member_card']['base_info']['promotion_url'] = $promotion_url;
                if ($accept_category) $requestCouponData['card']['member_card']['advanced_info']['use_condition']['accept_category'] = $accept_category;
                if ($reject_category) $requestCouponData['card']['member_card']['advanced_info']['use_condition']['reject_category'] = $reject_category;
                if (isset($can_use_with_other_discount)) $requestCouponData['card']['member_card']['advanced_info']['use_condition']['can_use_with_other_discount'] = (bool)$can_use_with_other_discount;
                if ($abstract) $requestCouponData['card']['member_card']['advanced_info']['abstract']['abstract'] = $abstract;
                if ($icon_url_list) $requestCouponData['card']['member_card']['advanced_info']['abstract']['icon_url_list'] = [$icon_url_list];
                if ($text_image_list) $requestCouponData['card']['member_card']['advanced_info']['text_image_list'] = json_decode($text_image_list, true);
                if ($time_limit) $requestCouponData['card']['member_card']['advanced_info']['time_limit'] = json_decode($time_limit, true);
                if ($business_service) $requestCouponData['card']['member_card']['advanced_info']['business_service'] = explode(',', $business_service);
                if (isset($auto_activate)) $requestCouponData['card']['member_card']['auto_activate'] = (bool)$auto_activate;
                if ($name_type) $requestCouponData['card']['member_card']['custom_field1']['name_type'] = $name_type;
                if ($url) $requestCouponData['card']['member_card']['custom_field1']['url'] = $url;
                if ($activate_url) $requestCouponData['card']['member_card']['activate_url'] = $activate_url;
                if ($custom_cell1) $requestCouponData['card']['member_card']['custom_cell1'] = json_decode($custom_cell1, true);
                if ($cost_money_unit) $requestCouponData['card']['member_card']['bonus_rule']['cost_money_unit'] = (int)$cost_money_unit;
                if ($increase_bonus) $requestCouponData['card']['member_card']['bonus_rule']['increase_bonus'] = (int)$increase_bonus;
                if ($max_increase_bonus) $requestCouponData['card']['member_card']['bonus_rule']['max_increase_bonus'] = (int)$max_increase_bonus;
                if ($init_increase_bonus) $requestCouponData['card']['member_card']['bonus_rule']['init_increase_bonus'] = (int)$init_increase_bonus;
                if ($cost_bonus_unit) $requestCouponData['card']['member_card']['bonus_rule']['cost_bonus_unit'] = (int)$cost_bonus_unit;
                if ($reduce_money) $requestCouponData['card']['member_card']['bonus_rule']['reduce_money'] = (int)$reduce_money;
                if ($least_money_to_use_bonus) $requestCouponData['card']['member_card']['bonus_rule']['least_money_to_use_bonus'] = (int)$least_money_to_use_bonus;
                if ($max_reduce_bonus) $requestCouponData['card']['member_card']['bonus_rule']['max_reduce_bonus'] = (int)$max_reduce_bonus;
                if ($discount) $requestCouponData['card']['member_card']['discount'] = (int)$discount;

                Log::info('公众号创建会员卡');
                Log::info($requestCouponData);
                Log::info(json_encode($requestCouponData, 320)); //不转义中文、/
                $result = $this->curl_post_https($req_url, json_encode($requestCouponData, 320));
                Log::info(json_encode($result));
                $result_arr = json_decode($result, true);
                $errmsg = $result_arr['errmsg'] ?? '创建会员卡失败';
                if ($result_arr['errcode'] == 0) {
                    $card_id = $result_arr['card_id'];
                    $insert_res = MembershipCardLists::create([
                        'store_id' => $requestAllData['store_id'],
                        'terminal_type' => $requestAllData['terminal_type'],
                        'card_id' => $card_id,
                    ]);
                    if (!$insert_res) {
                        return $this->responseDataJson(2, '微信会员卡创建记录失败');
                    }
                    return $this->responseDataJson(1, $errmsg, $result_arr);
                } else {
                    return $this->responseDataJson(2, $errmsg, $result_arr);
                }
                break;

            //支付宝会员卡
            case config("api.aliPay"):

                break;
        }
    }

    //获取会员卡信息
    public function getMemberCardInfo(Request $request)
    {
        $store_id = $request->get('storeId', ''); //系统门店id
        $terminal_type = $request->get('terminalType', ''); //会员卡类型(weChat-微信公众号;aliPay-支付宝)
        $card_code = $request->get('cardCode', ''); //会员code码
        $card_id = $request->get('cardId', ''); //会员卡号
        $status = $request->get('status', ''); //会员卡状态(0-未激活;1-激活)

        $where = [];
        if ($store_id) {
            $where[] = ['store_id', $store_id];
        }
        if ($terminal_type) {
            $where[] = ['terminal_type', $terminal_type];
        }
        if ($card_code) {
            $where[] = ['card_code', $card_code];
        }
        if ($card_id) {
            $where[] = ['card_id', $card_id];
        }
        if ($status) {
            $where[] = ['status', $status];
        }

        try {
            $card_info = MembershipCardLists::where($where)->get();
            if (!$card_info) {
                return $this->responseDataJson(2, '没有会员卡信息');
            }

            return $this->responseDataJson(1, '会员卡信息', $card_info);
        } catch (\Exception $e) {
            return $this->responseDataJson(-1, $e->getMessage().' | '.$e->getFile().' | '.$e->getLine());
        }
    }

    /**
     * 获取门店下的会员卡信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getStoreMemberCardInfo(Request $request){
        $requestAllData = $request->all();
        if(!isset($requestAllData['store_id']) || empty($requestAllData['store_id'])){
            return $this->responseDataJson(4002);
        }
        if(!isset($requestAllData['terminal_type']) || empty($requestAllData['terminal_type'])){
            return $this->responseDataJson(4003);
        }
        try {
            //查询该门店下的会员卡数据
            $card_info = MembershipCardLists::where(['store_id' => $requestAllData['store_id'] , 'terminal_type' => $requestAllData['terminal_type']])->orderBy("created_at","asc")->first();
            if (!$card_info) {
                return $this->responseDataJson(2, '没有会员卡信息');
            }
            //请求微信官方接口获取会员卡信息详情
            $access_token = $this->getWeChatAccessToken($this->weChatServerAppId,$this->weChatServerSecret);
            $access_token = json_decode($access_token,true);
            if(!isset($access_token['access_token'])){
                return $this->responseDataJson(2, 'access_token信息获取不正确');
            }
            $url = "https://api.weixin.qq.com/card/get?access_token=".$access_token['access_token'];
            $requestData = [
                'card_id' => $card_info->card_id
            ];
            $result = $this->curl_post_https($url, json_encode($requestData,JSON_UNESCAPED_UNICODE));
            $result = json_decode($result,true);
            if($result['errcode'] == 0){
                return $this->responseDataJson(1, '会员卡信息', $result);
            }else{
                return $this->responseDataJson(2, $result['errmsg']);
            }
        } catch (\Exception $e) {
            return $this->responseDataJson(-1, $e->getMessage().' | '.$e->getFile().' | '.$e->getLine());
        }
    }

    /**
     * 获取当前用户领取的会员卡
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserMemberCardInfo(Request $request){
        $requestAllData = $request->all();
        if(!isset($requestAllData['store_id']) || empty($requestAllData['store_id'])){
            return $this->responseDataJson(4002);
        }
        if(!isset($requestAllData['terminal_type']) || empty($requestAllData['terminal_type'])){
            return $this->responseDataJson(4003);
        }
        if(!isset($requestAllData['user_id']) || empty($requestAllData['user_id'])){
            return $this->responseDataJson(4001);
        }

        $type = $requestAllData['terminal_type'] == "weChat" ? 1 : 2;

        //查询门店下的会员卡
        $membership_card = DB::table("membership_card_lists")->where(['store_id' => $requestAllData['store_id'],'terminal_type' => $requestAllData['terminal_type']])->orderBy("created_at","asc")->first();
        if(!empty($membership_card)){
            $membership_card_user_lists = DB::table("membership_card_user_lists")->where(['user_id' => $requestAllData['user_id'],'member_card_type' => $type,'member_card_id' => $membership_card->card_id])->first();
            if(!empty($membership_card_user_lists)){
                return $this->responseDataJson(203,"用户已领取",['card_id' => $membership_card->card_id]);
            }else{
                return $this->responseDataJson(200,"用户未领取，可以进行领取",['card_id' => $membership_card->card_id]);
            }
        }else{
            return $this->responseDataJson(202,"该门店未创建会员卡");
        }
    }

    /**
     * 领取会员卡需要的签名信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMemberCardSignature(Request $request){
        $requestAllData = $request->all();
        if(!isset($requestAllData['store_id']) || empty($requestAllData['store_id'])){
            return $this->responseDataJson(4002);
        }
        if(!isset($requestAllData['terminal_type']) || empty($requestAllData['terminal_type'])){
            return $this->responseDataJson(4003);
        }
        if(!isset($requestAllData['user_id']) || empty($requestAllData['user_id'])){
            return $this->responseDataJson(4001);
        }
        if(!isset($requestAllData['card_id']) || empty($requestAllData['card_id'])){
            return $this->responseDataJson(202,"card_id不可为空");
        }

        switch ($requestAllData['terminal_type']) {
            //微信会员卡
            case config("api.weChat"):
                $config = [
                    'app_id' => $this->weChatServerAppId,
                    'secret' => $this->weChatServerSecret,
                    'response_type' => 'array',
                ];
                $app = Factory::officialAccount($config);
                $card = $app->card;
                $cards = [
                    ['card_id' => $requestAllData['card_id'],''],
                ];
                $json = $card->jssdk->assign($cards);
                $memberCardSignature = json_decode($json,true);
                return $this->responseDataJson(200,"获取成功",$memberCardSignature);
                break;
            //支付宝会员卡
            case config("api.aliPay"):
                $membership_card = DB::table("membership_card_lists")->where(['store_id' => $requestAllData['store_id'],'terminal_type' => $requestAllData['terminal_type'],'card_id' => $requestAllData['card_id']])->first();
                if(!empty($membership_card)){
                    if(!empty($membership_card->card_activateurl_apply)){
                        return $this->responseDataJson(200,"查询会员卡信息成功",['apply_card_url' => $membership_card->card_activateurl_apply]);
                    }else{
                        return $this->responseDataJson(202,"会员卡领卡链接不存在");
                    }
                }else{
                    return $this->responseDataJson(202,"该商家未创建会员卡");
                }
                break;
        }
    }


    /**
     * 记录用户领取会员卡记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function createUserMemberCardInfo(Request $request){
        $requestAllData = $request->all();
        if(!isset($requestAllData['store_id']) || empty($requestAllData['store_id'])){
            return $this->responseDataJson(4002);
        }
        if(!isset($requestAllData['terminal_type']) || empty($requestAllData['terminal_type'])){
            return $this->responseDataJson(4003);
        }
        if(!isset($requestAllData['user_id']) || empty($requestAllData['user_id'])){
            return $this->responseDataJson(4001);
        }
        if(!isset($requestAllData['card_id']) || empty($requestAllData['card_id'])){
            return $this->responseDataJson(202,"card_id不可为空");
        }
        $type = $requestAllData['terminal_type'] == config("api.weChat") ? 1 : 2;
        //查询门店下的会员卡
        $membership_card = DB::table("membership_card_lists")->where(['store_id' => $requestAllData['store_id'],'terminal_type' => $requestAllData['terminal_type'],'card_id' => $requestAllData['card_id']])->first();
        if(!empty($membership_card)){
            $membership_card_user_lists = DB::table("membership_card_user_lists")->where(['user_id' => $requestAllData['user_id'],'member_card_type' => $type,'member_card_id' => $requestAllData['card_id']])->first();
            if(!empty($membership_card_user_lists)){
                return $this->responseDataJson(202,"用户已领取，不可再次领取");
            }else{
                try{
                    $memberUserCard['user_id']          = $requestAllData['user_id'];
                    $memberUserCard['member_card_type'] = $type;
                    $memberUserCard['member_card_id']   = $requestAllData['card_id'];
                    $memberUserCard['member_card_code']      = isset($requestAllData['code']) ? $requestAllData['code'] : "";
                    $memberUserCard['member_code_cardExt']   = isset($requestAllData['cardExt']) ? $requestAllData['cardExt'] : "";
                    if($type == 2){
                        //支付宝会员卡
                        $memberUserCard['member_request_id']     = isset($requestAllData['request_id']) ? $requestAllData['request_id'] : "";
                    }
                    $memberUserCard['created_at']       = date("Y-m-d H:i:s",time());
                    $memberUserCard['updated_at']       = date("Y-m-d H:i:s",time());

                    //如果是支付宝会员卡领取，需要进行商户对用户进行开卡
                    if($type == 2){
                        Log::info("开卡type：".$type);
                        $userAliPayMembershipCardController = new UserAliPayMembershipCardController();
                        $userAliPayMembershipCardResult = $userAliPayMembershipCardController->aliPayMarketingCardOpen($requestAllData);
                        if($userAliPayMembershipCardResult['status'] == 200){
                            $memberUserCard['member_code_cardExt']   = isset($userAliPayMembershipCardResult['data']) ? $userAliPayMembershipCardResult['data'] : "";
                            $result = DB::table("membership_card_user_lists")->insert($memberUserCard);
                            if($result){
                                return $this->responseDataJson(200,"用户领取信息记录成功",$userAliPayMembershipCardResult['data']);
                            }else{
                                return $this->responseDataJson(202,"用户领取信息记录失败");
                            }
                        }else{
                            return $this->responseDataJson($userAliPayMembershipCardResult['status'],$userAliPayMembershipCardResult['message']);
                        }
                    }else{
                        $result = DB::table("membership_card_user_lists")->insert($memberUserCard);
                        if($result){
                            return $this->responseDataJson(200,"用户领取信息记录成功");
                        }else{
                            return $this->responseDataJson(202,"用户领取信息记录失败");
                        }
                    }
                }catch (\Exception $e){
                    return $this->responseDataJson(202,$e->getMessage());
                }
            }
        }else{
            return $this->responseDataJson(202,"未查询到该会员卡信息");
        }
    }


    //系统会员列表
    public function mb_lists(Request $request)
    {
        try {
            $token = $this->parseToken(); //
            $time_start = $request->get('time_start', '');
            $time_end = $request->get('time_end', '');
            $mb_id = $request->get('mb_id', ''); //会员卡号
            $mb_phone = $request->get('mb_phone', ''); //手机号

            $where = [];
            if ($time_start) {
                $time_start = date('Y-m-d H:i:s', strtotime($time_start));
                $where[] = ['mb_time', '>=', $time_start];
            }
            if ($time_end) {
                $time_end = date('Y-m-d H:i:s', strtotime($time_end));
                $where[] = ['mb_time', '<=', $time_end];
            }
            if ($mb_id) {
                $where[] = ['mb_id', '=', $mb_id];
            }
            if ($mb_phone) {
                $where[] = ['mb_phone', '=', $mb_phone];
            }

            $obj = MemberList::where($where);

            $data = $obj->orderBy('created_at', 'desc')
                ->get();

            return $this->responseDataJson(1, '数据返回成功', $data);
        } catch (\Exception $e) {
            return $this->responseDataJson(-1, '系统错误', $e->getMessage().' | '.$e->getFile().' | '.$e->getLine());
        }
    }


    //系统会员创建or更新
    public function member_update(Request $request)
    {
        try {
            $store_id = $request->post('store_id', '');
            $open_id = $request->post('open_id', '');
            $ways_source = $request->post('ways_source', ''); //alipay,weixin,xcx_openid
            $mb_name = $request->post('mb_name', '');
            $mb_phone = $request->post('mb_phone', '');
            $merchant_id = $request->post('merchant_id', '');

            if(!isset($open_id) || empty($open_id)){
                return $this->responseDataJson(202, 'open_id必传');
            }
            if(!isset($store_id) || empty($store_id)){
                return $this->responseDataJson(202, '门店ID必传');
            }
//            if(!isset($mb_phone) || empty($mb_phone)){
//                return $this->responseDataJson(202, '会员手机号必传');
//            }

            $store = Store::where('store_id', $store_id)
                ->select('config_id', 'merchant_id')
                ->first();
            if (!$store) {
                return $this->responseDataJson(202, '门店不存在');
            }

            $ali_user_id = "";
            $xcx_openid = "";
            $wx_openid = "";
            $MemberList = "";
            $config_id = $store->config_id;
            $sotre_merchant_id = $store->merchant_id;

            if ($ways_source == "alipay") {
                $ali_user_id = $open_id;
                $MemberList = MemberList::where('store_id', $store_id)
                    ->where('ali_user_id', $open_id)
                    ->first();
            }

            if ($ways_source == "weixin") {
                $wx_openid = $open_id;
                $MemberList = MemberList::where('store_id', $store_id)
                    ->where('wx_openid', $open_id)
                    ->first();
            }

            if ($ways_source == "xcx_openid") {
                $xcx_openid = $open_id;
                $MemberList = MemberList::where('store_id', $store_id)
                    ->where('xcx_openid', $open_id)
                    ->first();
            }

            if ($MemberList) {
                //返回数据
                $re_data = [
                    'store_id' => $store_id,
                    'config_id' => $config_id,
                    'mb_jf' => $MemberList->mb_jf,
                    'mb_id' => $MemberList->mb_id,
                    'mb_money' => $MemberList->mb_money,
                    'xcx_openid' => $xcx_openid,
                    'wx_openid' => $wx_openid,
                    'ali_user_id' => $ali_user_id,
                    'mb_ver' => $MemberList->mb_ver,
                    'mb_ver_desc' => $MemberList->mb_ver_desc,
                ];
                if ($mb_phone) $re_data['mb_phone'] = $mb_phone;
                if ($mb_name) $re_data['mb_name'] = $mb_name;

                $in_sert_data = [
                    'store_id' => $store_id,
                    'config_id' => $config_id
                ];
                if ($mb_phone) $in_sert_data['mb_phone'] = $mb_phone;
                if ($mb_name) $in_sert_data['mb_name'] = $mb_name;
                $res = $MemberList->update($in_sert_data);
                if ($res) {
                    return $this->responseDataJson(200, '数据更新成功', $re_data);
                } else {
                    return $this->responseDataJson(202, '数据更新失败', $re_data);
                }
            } else {
                //会员不存在开卡会员
                $mb_id = date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));

                $in_sert_data = [
                    'store_id' => $store_id,
                    'config_id' => $config_id,
                    'merchant_id' => (int)$merchant_id ?? (int)$sotre_merchant_id,
                    'mb_id' => $mb_id,
                    'mb_status' => '1',
                    'mb_ver' => '1',
                    'mb_ver_desc' => '普通会员',

                    'mb_logo' => url('/member/mrtx.png'),
                    'mb_jf' => 0,
                    'mb_money' => '0.00', //储值金额
                    'mb_time' => date('Y-m-d H:i:s', time()),
                    'pay_counts' => 1,
                    'pay_moneys' => 0
                ];
                if ($mb_name)  {
                    $in_sert_data['mb_name'] = $mb_name;
                    $in_sert_data['mb_nick_name'] = $mb_name;
                }
                if ($mb_phone) $in_sert_data['mb_phone'] = $mb_phone;
                if ($xcx_openid) $in_sert_data['xcx_openid'] = $xcx_openid;
                if ($wx_openid) $in_sert_data['wx_openid'] = $wx_openid;
                if ($ali_user_id) $in_sert_data['ali_user_id'] = $ali_user_id;
                $res = MemberList::create($in_sert_data);

                //返回数据
                $re_data = [
                    'mb_id' => $mb_id,
                    'store_id' => $store_id,
                    'config_id' => $config_id,
                    'mb_name' => $mb_name,
                    'mb_phone' => $mb_phone,
                    'mb_jf' => 0,
                    'mb_money' => '0.00',//储值金额
                    'wx_openid' => $wx_openid,
                    'ali_user_id' => $ali_user_id,
                    'mb_ver' => '1',
                    'mb_ver_desc' => '普通会员'
                ];
                if ($res) {
                    return $this->responseDataJson(200, '创建会员成功', $re_data);
                } else {
                    return $this->responseDataJson(202, '创建会员失败', $re_data);
                }
            }
        } catch (\Exception $ex) {
            return $this->responseDataJson(-1, '系统错误', $ex->getMessage().'|'.$ex->getLine());
        }
    }


    //商家充值-c扫b
    public function member_cz(Request $request)
    {
        try {
            $token = $this->parseToken();
            $store_id = $request->post('store_id'); //门店ID
            $cz_s_money = $request->post('cz_s'); //充值送金额
            $cz_money = $request->post('cz'); //充值金额
            $open_id = $request->post('open_id'); //支付宝微信标示
            $mb_id = $request->post('mb_id', ''); //会员卡号
            $ways_type = $request->post('ways_type'); //通道类型
            $merchant_id = $request->post('merchant_id', '0'); //收银员id
            $pay_method = $request->post('pay_method', ''); //系统支付方式;alipay_face-支付宝刷脸;weixin_face-微信刷脸;wx_applet-微信小程序;ali_applet-支付宝小程序

            $cz_trade_no = 'CZ' . date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));

            if (!isset($store_id) && empty($store_id)) {
                return $this->responseDataJson(2, '门店ID不能为空');
            }
            if (!isset($cz_s_money) && empty($cz_s_money)) {
                return $this->responseDataJson(2, '充值送金额不能为空');
            }
            if (!isset($cz_money) && empty($cz_money)) {
                return $this->responseDataJson(2, '充值金额不能为空');
            }
            if (!isset($mb_id) && empty($mb_id)) {
                return $this->responseDataJson(2, '会员卡号不能为空');
            }
            if (!isset($ways_type) && empty($ways_type)) {
                return $this->responseDataJson(2, '通道类型不能为空');
            }

            $store = Store::where('store_id', $store_id)
                ->select('config_id', 'store_name', 'pid', 'user_id', 'is_delete', 'is_admin_close', 'is_close')
                ->first();
            if (!$store) {
                return $this->responseDataJson(2, '没有关联认证门店请联系服务商');
            }

            //关闭的商户禁止交易
            if ($store->is_close || $store->is_admin_close || $store->is_delete) {
                return $this->responseDataJson(2, '商户已经被服务商关闭');
            }

            $config_id = $store->config_id;
            $store_name = $store->store_name;
            $store_pid = $store->pid;
            $tg_user_id = $store->user_id;
            $where = [];
            $obj_ways = new PayWaysController();
            $ways = $obj_ways->ways_type($ways_type, $store_id, $store_pid);
            if (!$ways) {
                return $this->responseDataJson(2, '没有开通此类型通道');
            }

            //验证扣费模式
            list($isRun,$error)=\App\Services\Store\StoreSignService::validateSign((string)$ways->store_id,(string)$ways->company);
            if($isRun==false){
                return $this->responseDataJson(2, $error);
            }

            $ways_source = $ways->ways_source;
            $ways_type = $ways->ways_type;
            $ways_source_desc = $ways->ways_source;
            $company = $ways->company;
            $rate = $ways->rate;
            $fee_amount = $ways->rate * $cz_money / 100;
            $ali_user_id = "";
            $wx_openid = "";
            $xcx_openid = "";

            $MemberList = MemberList::where('store_id', $store_id)
                ->where('mb_id', $mb_id)
                ->select('mb_phone', 'mb_money')
                ->first();

            //不是会员
            $mb_phone = "";
            $mb_money = "";
            if (!$MemberList) {
                //积分赠送情况
                $MemberSetJf = MemberSetJf::where('store_id', $store_id)
                    ->first();

                $new_mb_jf = 0;
                if ($MemberSetJf) {
                    $new_mb_jf = $MemberSetJf->new_mb_s_jf;
                }

                $in_sert_data = [
                    'store_id' => $store_id,
                    'merchant_id' => $merchant_id,
                    'config_id' => $config_id,
                    'mb_id' => $mb_id,
                    'mb_status' => '1',
                    'mb_ver' => '1',
                    'mb_ver_desc' => '普通会员',
                    'mb_name' => "未设置",
                    'mb_phone' => "未绑定",
                    'mb_nick_name' => "未设置",
                    'mb_logo' => url('/member/mrtx.png'),
                    'mb_jf' => $new_mb_jf,
                    'mb_money' => '0.00', //储值金额
                    'mb_time' => date('Y-m-d H:i:s', time()),
                    'pay_counts' => 1,
                    'pay_moneys' => $cz_money,
                    'wx_openid' => $wx_openid,
                    'xcx_openid' => $xcx_openid,
                    'ali_user_id' => $ali_user_id,
                ];
                MemberList::create($in_sert_data);
            } else {
                $mb_phone = $MemberList->mb_phone;
                $mb_money = $MemberList->mb_money;
            }

            $data = [
                'merchant_name' => '会员充值',
                'store_id' => $store_id,
                'merchant_id' => $merchant_id,
                'config_id' => $config_id,
                'store_name' => $store_name,
                'store_pid' => $store_pid,
                'tg_user_id' => $tg_user_id,
                'total_amount' => $cz_money,
                'shop_price' => $cz_money,
                'remark' => '会员充值',
                'device_id' => 'member_cz',
                'shop_name' => '会员充值',
                'shop_desc' => '会员充值',
                'open_id' => $open_id,
                'ways_type' => $ways_type,
                'other_no' => $cz_trade_no,
                'notify_url' => '',
                'pay_method' => $pay_method,
            ];
            $obj = new PayBaseController();
            $re = $obj->qr_auth_pay_public($data, $ways);
            $re_arr = json_decode($re, true);
            $out_trade_no = isset($re_arr['out_trade_no']) ? $re_arr['out_trade_no'] : "";

            //充值入库
            if ($re_arr['status'] == 1) {
                $inser_data = [
                    'store_id' => $store_id,
                    'store_name' => $store_name,
                    'ways_source_desc' => $ways_source_desc,
                    'ways_source' => $ways_source,
                    'company' => $company,
                    'rate' => $rate,
                    'cz_money' => $cz_money,//'充值支付金额',
                    'cz_s_money' => $cz_s_money,//'充值送金额',
                    'pay_status' => 2,
                    'pay_time' => '',
                    'cz_type' => $cz_s_money > 0 ? 2 : 1,
                    'cz_type_desc' => $cz_s_money > 0 ? '充值送' : '普通充值',
                    'total_amount' => $cz_money,//'订单总金额',
                    'fee_amount' => $fee_amount,//'手续费',
                    'receipt_amount' => $cz_money - $fee_amount,//'商家实收',
                    'out_trade_no' => $cz_trade_no,
                    'mb_id' => $mb_id,//会员ID
                    'mb_phone' => $mb_phone,//会员手机号
                ];
                MemberCzList::create($inser_data);
            }
            $re_arr['mb_money'] = $mb_money;

            return json_encode($re_arr);
        } catch (\Exception $e) {
            return json_encode([
                'status' => -1,
                'message' => $e->getMessage().' | '.$e->getFile().' | '.$e->getLine()
            ]);
        }
    }


}
